<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <title></title>
</head>
<body>
<div id="app"></div>

<!-- react核心库 -->
<script src="../lib/react.development.js"></script>
<!-- react操作dom -->
<script src="../lib/react-dom.development.js"></script>
<!-- jsx转js -->
<script src="../lib/babel.min.js"></script>
<script type="text/babel">
  class Like extends React.Component {
    constructor(props) {
      super(props)
      console.log("like---constructor")
      this.state = {
        num: 0
      }
    }

    // 组件即将挂载
    componentWillMount() {
      console.log("like---componentWillMount")
    }

    // 组件挂载完毕
    componentDidMount() {
      console.log("like---componentDidMount")
    }

    // 组件即将卸载
    componentWillUnmount() {
      console.log("like---componentWillUnMount")
    }

    // 组件接收到新的props时
    componentWillReceiveProps() {
      console.log("like---componentWillReceiveProps")
    }

    /**
     * 组件状态更新前调用，首次渲染和forceUpdate不会触发
     * setState()会触发
     *
     * @returns {boolean} true-执行render，false-不执行
     */
    shouldComponentUpdate() {
      console.log("like---shouldComponentUpdate")
      return true
    }

    componentDidUpdate() {
      console.log("like---componentDidUpdate")
    }

    addLike = () => {
      this.setState({num: ++this.state.num})
    }

    destroy = () => {
      ReactDOM.unmountComponentAtNode(document.getElementById("app"))
    }

    force = () => {
      this.forceUpdate()
    }

    // 渲染
    render() {
      console.log("like---render")
      return (
        <div>
          <h3>{this.props.username}，点赞数: {this.state.num}</h3>
          <button onClick={this.addLike}>+1</button><br/>
          <button onClick={this.destroy}>卸载</button><br/>
          <button onClick={this.force}>不改变状态，强制更新</button>
        </div>
      )
    }
  }

  class Page extends React.Component {
    state = {
      title: "Welcome",
      username: "admin"
    }

    changeUsername = () => {
      let username = this.state.username === "admin" ? "test" : "admin"
      this.setState({username: username})
    }
    render() {
      return (
        <div>
          <h3>{this.state.title}</h3>
          <button onClick={this.changeUsername}>切换用户</button>
          <Like username={this.state.username}/>
        </div>
      )
    }

  }

  ReactDOM.render(<Page/>, document.getElementById("app"))
</script>
</body>
</html>